package com.feng.system.controller;

import com.feng.common.api.ResponseResult;
import com.feng.common.validation.groups.Update;
import com.feng.system.dto.RoleParam;
import com.feng.system.service.RoleService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.groups.Default;
import java.util.Set;

/**
 * @author Feng
 * @since 2022/4/20 15:56
 */
@RestController
@RequestMapping("/role")
public class RoleAdminController {

    @Autowired
    RoleService roleService;

    @ApiOperation("根据角色ID获取权限列表")
    @GetMapping("/permissions/{id}")
    @PreAuthorize("@er.check('role:list')")
    public ResponseResult getPermissionsByRoleId(@PathVariable Long id) {
        return ResponseResult.success(roleService.getPermissionsByRoleId(id));
    }

    @ApiOperation("根据角色名模糊查询角色信息(不包括角色权限)")
    @GetMapping
    @PreAuthorize("@er.check('role:list')")
    public ResponseResult getPermissionsByRoleId(String keyWord,
                                                 @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                 @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        return ResponseResult.success(roleService.search(keyWord, pageNum, pageSize));
    }

    @ApiOperation("添加单个角色")
    @PostMapping
    @PreAuthorize("@er.check('role:add')")
    public ResponseResult add(@RequestBody @Validated RoleParam param) {
        roleService.addRole(param.getRoleName(), param.getLevel());
        return ResponseResult.success();
    }

    @ApiOperation("修改角色")
    @PutMapping
    @PreAuthorize("@er.check('role:update')")
    public ResponseResult update(@RequestBody @Validated({Default.class, Update.class}) RoleParam param) {
        roleService.updateRoleById(param.getRoleId(), param.getRoleName(), param.getLevel());
        return ResponseResult.success();
    }

    @ApiOperation("删除多个角色")
    @DeleteMapping
    @PreAuthorize("@er.check('role:delete')")
    public ResponseResult delete(Set<Long> ids) {
        roleService.deleteByRoleIds(ids);
        return ResponseResult.success();
    }
}
